﻿#include "database.h"
#include "zhidebug.h"
#include <QSqlError>
#include <QVariant>
#include <QDebug>

Database::Database()
{

}

Database::Database(int dbtype)
{
    qdatabase = new QSqlDatabase();
    //qDebug() << QSqlDatabase::drivers();
    if(dbtype == Database::MYSQL){
        *qdatabase=QSqlDatabase::addDatabase("QMYSQL");
        qdatabase->setHostName("127.0.0.1");
        qdatabase->setUserName("root");
        qdatabase->setPassword("123456");
        qdatabase->setDatabaseName("qtcms");
    }

    if(qdatabase->open())
        {
            ZhiDebug::Info("Database connected successfully!");
            query = new QSqlQuery(*qdatabase);
            return;
        }
    else
        {
            ZhiDebug::Info("Database connected failed! Due to: " + qdatabase->lastError().text());
            return;
        }
}

void Database::close()
{

    if(qdatabase->isOpen()){
        if(!query->isActive()){
            query->clear();
            query = nullptr;
        }
        qdatabase->close();
    }


    delete qdatabase;
    qdatabase = nullptr;


    QString name;
    {
        name = QSqlDatabase::database().connectionName();
    }
    QSqlDatabase::removeDatabase(name);
}

void Database::createtable()
{

    //query.exec("create table user(name VARCHAR(30) PRIMARY KEY UNIQUE NOT NULL,passward VARCHAR(30))");

    /*创建root用户*/
    //query.exec("insert into user value('root', 'root')");
}


bool Database::validataUser(QString username, QString password)
{
    QString cmd = QString("select count(*) as count from q_users where uname = '%1' AND upass = '%2'").arg(username).arg(password);
    ZhiDebug::Info("SQL:" + cmd);
    query->exec(cmd);

    if(query->next())
    {
        int count = query->value(0).toInt();
        if(count == 1){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
